library(ggplot2)
library(dplyr)
library(modelsummary)
library(kableExtra)
library(stringr)
library(fixest)
library(stargazer)
library(gridExtra)
library(flextable)

df_wide <- readRDS("data/df_wide.rds")

df_wide <- df_wide %>% filter(d_affiliated == 1)

m1 <- feols(trust_in_opposing_parties ~ feeling_toward, df_wide, 
            weights = df_wide$meta_Weight)
m2 <- feols(trust_in_opposing_parties ~ close_num, df_wide,
            weights = df_wide$meta_Weight)

m3 <- feols(trust_in_opposing_parties ~ feeling_toward | dem_country_code, df_wide, 
            weights = df_wide$meta_Weight)
m4 <- feols(trust_in_opposing_parties ~ close_num | dem_country_code, df_wide, 
            weights = df_wide$meta_Weight)

m5 <- feols(trust_in_opposing_parties ~ feeling_toward + dem_age + 
              dem_gender + dem_city_or_rural + lrscale + dem_education_level + 
              high_income | dem_country_code + party_affil, df_wide,
            weights = df_wide$meta_Weight)
m6 <- feols(trust_in_opposing_parties ~ close_num + dem_age + 
              dem_gender + dem_city_or_rural + lrscale + dem_education_level + 
              high_income | dem_country_code + party_affil, df_wide,
            weights = df_wide$meta_Weight)


options("modelsummary_format_numeric_latex" = "plain")
models <- list("(1)" = m1, "(2)" = m2, "(3)" = m3, "(4)" = m4, "(5)" = m5, "(6)" = m6)
tab <- modelsummary(models, output = 'html', stars = TRUE,
                    coef_rename = c("feeling_toward" = "Feeling", 
                                    "close_num" = "Social distance", 
                                    "dem_age" = "Age", 
                                    "dem_gendermale" = "Male", 
                                    "dem_city_or_ruralrural" = "Rural", 
                                    "lrscale" = "Left-right scale", 
                                    "dem_education_levelno" = "No education", 
                                    "dem_education_levellow" = "Low education",
                                    "dem_education_levelmedium" = "Medium education",
                                    # "household_incomelow" = "Low income", 
                                    # "household_incomemedium" = "Medium income",
                                    # "household_incomePrefer not to say" = "Income missing",
                                    "high_income" = "High income"),
                    coef_omit = c("(Intercept)"),
                    gof_omit = "AIC|BIC|Log|Pseudo|Adj|Within|Std.Errors", 
                    statistic = "p.value") %>%
  add_header_above(c(" " = 1, "DV: Trust in opposing parties (1-5)"= 6), line = T, italic = F)


kableExtra::save_kable(tab, file = "tables/TableA10.html")

